package com.rich.dmr.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.rich.dmr.R;
import com.rich.dmr.common.RichStaggeredGridLayoutManager;
import com.rich.dmr.model.RxGroupModel;
import com.rich.dmr.ui.view.CommonDialog;
import com.rich.dmr.ui.view.SimpleToolbar;
import com.rich.dmr.utils.DataBaseUtils;
import com.rich.dmr.utils.Log;
import com.rich.dmr.utils.SoundPoolUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import rich.dmr.DmrManager;

public class RxGroupFragment extends Fragment implements View.OnClickListener {
    private String TAG = "rich---RxGroupFragment";
    private List<RxGroupModel> rxGroupModels = new ArrayList<>();
    private Context mContext;
    private DmrManager dmrManager;
    private DataBaseUtils mDataBaseUtils;
    private RxGroupListGridAdapter adapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        Log.d(TAG, "onAttach");
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        mDataBaseUtils = DataBaseUtils.getInstance(mContext);
        rxGroupModels.addAll(mDataBaseUtils.findRxGroupList());
        dmrManager = (DmrManager) mContext.getSystemService("dmrservice");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View root = inflater.inflate(R.layout.fragment_rx_group_list, container, false);
        SimpleToolbar simpleToolbar = root.findViewById(R.id.rx_list_tools_bar);
        simpleToolbar.setMainTitle("Rx list");
        simpleToolbar.setLeftTitleDrawable(R.mipmap.icon_left);
        simpleToolbar.setLeftTitleClickListener(this);
        simpleToolbar.setRightTitleDrawable(R.mipmap.icon_plus);
        simpleToolbar.setRightTitleClickListener(this);

        final RecyclerView recyclerView = root.findViewById(R.id.rx_group_list);
        recyclerView.setLayoutManager(new RichStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        adapter = new RxGroupListGridAdapter();
        recyclerView.setAdapter(adapter);
        return root;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_left_title:
                getActivity().finish();
                break;
            case R.id.txt_right_title:
                initDialog();
                break;

            default:
                break;
        }
    }

    class RxGroupListGridAdapter extends RecyclerView.Adapter<RxGroupListGridAdapter.LinearViewHolder> {
        private String TAG = "rich---RxGroupListGridAdapter";
        private boolean onBind;

        private RxGroupListGridAdapter() {

        }

        @NonNull
        @Override
        public RxGroupListGridAdapter.LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Log.d(TAG, "onCreateViewHolder");
            return new RxGroupListGridAdapter.LinearViewHolder(LayoutInflater.from(mContext).
                    inflate(R.layout.item_rv_rx_group_list, parent, false));
        }

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public void onBindViewHolder(@NonNull final RxGroupListGridAdapter.LinearViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            Log.d(TAG, "onBindViewHolder");
            if (rxGroupModels.size() == 0) {
                return;
            }
            holder.rxGroupDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dmrManager.getGroupList().equals(rxGroupModels.get(position).getRxGroupId())) {
                        Toast.makeText(mContext, "Current rx list can't delete", Toast.LENGTH_SHORT).show();
                    } else {
                        mDataBaseUtils.deleteRxListById(rxGroupModels.get(position).getId());
                        rxGroupModels.clear();
                        rxGroupModels.addAll(mDataBaseUtils.findRxGroupList());
                        notifyDataSetChanged();
                    }
                }
            });

            holder.rxGroupSelect.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:

                            return true;
                        case MotionEvent.ACTION_MOVE:

                            return true;
                        case MotionEvent.ACTION_UP:
                            dmrManager.setGroupList(rxGroupModels.get(position).getRxGroupId());
                            dmrManager.flush();
                            SoundPoolUtils.getInstance(mContext).playSound(false);
                            notifyDataSetChanged();
                            return true;
                        case MotionEvent.ACTION_CANCEL:

                            return true;

                    }
                    return false;
                }
            });

      /*      holder.rxGroupSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Log.d(TAG, "onCheckedChanged isChecked" + isChecked);
                    if (isChecked) {
                        //dmrManager.setGroupList(rxGroupModels.get(position).getRxGroupId());
                        //dmrManager.flush();
                        //SoundPoolUtils.getInstance(mContext).playSound(false);
                        Log.d(TAG, "position=" + position);
                    } else {
                        //dmrManager.setGroupList("16776414/1");
                        //dmrManager.flush();
                        //SoundPoolUtils.getInstance(mContext).playSound(false);
                    }
                    if (!onBind) {
                        //notifyDataSetChanged();
                    }
                }
            });*/
            onBind = true;
            holder.rxGroupItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     dmrManager.setGroupList(rxGroupModels.get(position).getRxGroupId());
                     dmrManager.flush();
                     SoundPoolUtils.getInstance(mContext).playSound(false);
                     notifyDataSetChanged();
                }
            });

            if (dmrManager.getGroupList().equals(rxGroupModels.get(position).getRxGroupId())) {
                holder.rxShowLine.setBackgroundResource(R.drawable.shape_online);
                holder.rxGroupName.setTextColor(Color.RED);
            } else {
                holder.rxShowLine.setBackgroundResource(R.drawable.shape_setting_offline);
                holder.rxGroupName.setTextColor(Color.WHITE);
            }

            holder.rxGroupName.setText(rxGroupModels.get(position).getRxGroupName());
            holder.rxGroupId.setText(rxGroupModels.get(position).getRxGroupId());
            holder.rxGroupSelect.setChecked(dmrManager.getGroupList().equals(rxGroupModels.get(position).getRxGroupId()));
            onBind = false;
        }

        @Override
        public int getItemCount() {
            return rxGroupModels.size();
        }

        public class LinearViewHolder extends RecyclerView.ViewHolder {
            private TextView rxGroupName;
            private TextView rxGroupId;
            private TextView rxShowLine;
            private ImageView rxGroupDelete;
            private CheckBox rxGroupSelect;
            private LinearLayout rxGroupItem;

            private LinearViewHolder(View itemView) {
                super(itemView);
                rxGroupName = itemView.findViewById(R.id.rx_group_name);
                rxGroupId = itemView.findViewById(R.id.rx_group_id);
                rxShowLine = itemView.findViewById(R.id.rx_group_show_online);
                rxGroupDelete = itemView.findViewById(R.id.rx_group_delete);
                rxGroupSelect = itemView.findViewById(R.id.rx_group_select);
                rxGroupItem = itemView.findViewById(R.id.rv_rx_group_item_view);
            }
        }
    }

    private void initDialog() {
        final CommonDialog dialog = new CommonDialog(getActivity());
        dialog.setNickName("RxName")
                .setNickId("RxId")
                .setInputType(InputType.TYPE_CLASS_DATETIME)
                .setTitle("Create Rx Group")
                .setSingle(false).setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                String rxGroupName = dialog.getCommonName().getText().toString().trim();
                String rxGroupId = dialog.getCommonId().getText().toString().trim();
                if (!TextUtils.isEmpty(rxGroupName) && !TextUtils.isEmpty(rxGroupId)) {
                    Pattern pattern = Pattern.compile("(\\d{1,8}/?){1,32}");
                    boolean isMatcher = pattern.matcher(rxGroupId).matches();
                    if (!isMatcher) {
                        Toast.makeText(mContext, "Rx list illegal.", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String[] rxArray = rxGroupId.split("/");
                    Log.d(TAG, "length=" + rxArray.length);
                    for (String str : rxArray) {
                        if (str.length() > 8) {
                            Toast.makeText(mContext, "Group invalid.", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        int group = Integer.valueOf(str);
                        if (group <= 0 || group > 16776415) {
                            Toast.makeText(mContext, "Group invalid.", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Log.d(TAG, "group=" + group);
                    }
                    int count = mDataBaseUtils.findRxGroup(rxGroupId);
                    if (count > 0) {
                        Toast.makeText(mContext, "Rx list already exist.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    mDataBaseUtils.insertRxList(rxGroupName, rxGroupId);
                    rxGroupModels.clear();
                    rxGroupModels.addAll(mDataBaseUtils.findRxGroupList());
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                    Toast.makeText(getActivity(), "Save success.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "data is null.", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onNegativeClick() {
                dialog.dismiss();
                Toast.makeText(getActivity(), "Cancel", Toast.LENGTH_SHORT).show();
            }
        }).show();
    }
}